// Package database @program: chat
//@author: edte
//@create: 2021-12-28 21:00
package database

import (
	log2 "chat/log"
	"chat/tools"
	"context"
	"errors"
	"fmt"
	"github.com/go-redis/redis/v8"
	"strconv"
)

func QueryChatMessage(ctx context.Context, roomId int, userId int) ([]string, error) {

	redisPath := tools.GetEnv("REDIS_PATH", "localhost:6379")
	redisPD := tools.GetEnv("REDIS_PASSWORD", "")
	rdb := redis.NewClient(&redis.Options{
		Addr:     redisPath,
		Password: redisPD, // no password set
		DB:       2,       // use default DB
		//PoolSize: 500, // 连接池大小
	})
	result, err := rdb.SIsMember(ctx, strconv.Itoa(roomId), userId).Result()
	if err != nil {
		writeLog, err2 := log2.WriteLog(ctx, "chat", "QueryChatMessage", "userid:"+strconv.Itoa(userId)+" roomid:"+strconv.Itoa(roomId), "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return nil, err
	}
	if result == false {
		writeLog, err2 := log2.WriteLog(ctx, "chat", "QueryChatMessage", "userid:"+strconv.Itoa(userId)+" roomid:"+strconv.Itoa(roomId), "Debug", "If you have not joined the chat room, you have no permission to obtain message records")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return nil, errors.New("未加入聊天室,无权限获取消息记录")
	}
	rdb2 := redis.NewClient(&redis.Options{
		Addr:     redisPath,
		Password: redisPD, // no password set
		DB:       4,       // use default DB
		//PoolSize: 500, // 连接池大小
	})
	messages, err := rdb2.LRange(ctx, strconv.Itoa(roomId), -200, -1).Result()
	if err != nil {
		writeLog, err2 := log2.WriteLog(ctx, "chat", "QueryChatMessage", "userid:"+strconv.Itoa(userId)+" roomid:"+strconv.Itoa(roomId), "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return nil, err
	}
	return messages, err
}

func QueryChatMessage2(ctx context.Context, roomId int) ([]string, error) {
	redisPath := tools.GetEnv("REDIS_PATH", "localhost:6379")
	redisPD := tools.GetEnv("REDIS_PASSWORD", "")
	rdb2 := redis.NewClient(&redis.Options{
		Addr:     redisPath,
		Password: redisPD, // no password set
		DB:       3,       // use default DB
		//PoolSize: 500, // 连接池大小
	})
	messages, err := rdb2.LRange(ctx, strconv.Itoa(roomId), 0, -1).Result()
	if err != nil {
		writeLog, err2 := log2.WriteLog(ctx, "chat", "MasterAddUser", "roomid:"+strconv.Itoa(roomId), "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return nil, err
	}
	return messages, err
}
